
<template>
	<view>
		<cu-custom :bgColor="'bg-'+theme.backgroundColor" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">秒杀详情</block>
		</cu-custom>
		<view class="cu-card article no-card">
			<image class="cu-avatar radius seckill-image" :src="seckillInfo.picUrl"></image>
			<view class="padding" :class="'bg-'+theme.backgroundColor">
				<view class="action">{{seckillInfo.name}}</view>
				<view class="flex align-center justify-between margin-top">
					<view>
						<view class="text-price text-bold text-xl text-white">{{seckillInfo.seckillPrice}}</view>
						<view class="text-price text-decorat text-white">{{seckillInfo.goodsSku.salesPrice}}</view>
					</view>
					<view class="cu-item" v-if="seckillInfo.seckillHall&&outTime>0">
						<view class="text-sm margin-left-xs padding-bottom-xs">距离本场结束还剩：</view>
						<count-down class="bg-white round padding-xs margin-left-lg text-xs" :outTime="outTime"
						@countDownDone="countDownDone"></count-down>
					</view>
					<view @click="shareShowFun" class="text-sm text-white flex align-center">
						<view class="cuIcon-share"></view>
						<text class="margin-left-xs">分享</text>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-item bg-white">
			<view class="content padding">
				<view class="desc">
					<view class="text-black overflow-2">{{seckillInfo.goodsSpu.name}}</view>
					<view class="text-gray text-sm overflow-1 margin-top-xs" v-if="seckillInfo.goodsSku.specs.length > 0">{{specInfo}}</view>
					<view class="flex justify-between margin-top-sm">
						<text class="text-sm text-gray">已售{{seckillInfo.seckillNum}}</text>
						<text class="text-sm text-gray">限量{{seckillInfo.limitNum}}</text>
						<text class="text-blue text-sm" @tap="ruleShow">秒杀规则</text>
					</view>
					<!-- <view class="cu-tag bg-red radius sm margin-left" v-if="seckillInfo.goodsSpu.freightTemplat.type == '2'">包邮</view> -->
				</view>
			</view>
		</view>
		<view class="bg-white margin-top-xs" v-if="shopInfo.id">
			<navigator class="padding" hover-class="none" :url="'/pages/shop/shop-detail/index?id=' + shopInfo.id">
				<text class="text-black text-sm">{{shopInfo.name}}</text>
				<view class="margin-top-sm flex align-center">
					<view class="cu-avatar df radius" :style="'background-image:url(' + shopInfo.imgUrl + ')'"></view>
					<view class="margin-left-sm">
						<text class="text-sm text-gray overflow-1">{{shopInfo.address}}</text>
						<text class="text-sm text-gray">{{shopInfo.phone}}</text>
					</view>
				</view>
			</navigator>
		</view>
		<view class="cu-card no-card margin-top-xs">
			<view class="cu-item">
				<view class="cu-bar bg-white">
					<view class="content">商品信息</view>
				</view>
				<view class="bg-white">
					<jyf-parser :html="article_description"></jyf-parser>
				</view>
				<view class="cu-load bg-gray to-down">已经到底啦...</view>
			</view>
		</view>
		<view class="cu-bar bg-white tabbar border shop foot">
		  <button open-type="contact" class="action bg-white"><view class="cuIcon-servicefill"></view>客服</button>
			<!-- <view class="submit" @tap="tobuy">
				<view class="cu-btn bg-orange round shadow-blur">
					<view class="text-price">{{seckillInfo.goodsSku.salesPrice}}</view>
					<view>原价购买</view>
				</view>
			</view> -->
			<view @tap="toSeckillBuy">
				<view class="cu-btn round shadow-blur margin-right" :class="'bg-' + (outTime>0  ? 'red' : 'gray') + ' submit'">
					<view class="text-price">{{seckillInfo.seckillPrice}}</view>
					<view>{{outTime>0 ? '立即购买' : outTime==0 ? '即将开始' : '已结束'}}</view>
				</view>
			</view>
		</view>
		<!-- html转wxml -->
		<poster id="poster" ref='posterRef' :hide-loading="false" :preload="false" :config="posterConfig" @success="onPosterSuccess"
		 @fail="onPosterFail"></poster>
		<view :class="'cu-modal bottom-modal ' + shareShow" @tap="shareHide">
			<view class="cu-dialog" @tap.stop>
				<view class="cu-bar bg-white">
					<view class="action text-green"></view>
					<view class="action text-red" @tap="shareHide">取消</view>
				</view>
				<view class="padding flex flex-direction">
					<share-friends :shareObj="{
								title: seckillInfo.shareTitle,
								desc: seckillInfo.goodsSpu.name,
								imgUrl: seckillInfo.picUrl,
								url: curLocalUrl,
						}"></share-friends>
					<button class="cu-btn margin-tb-sm lg round shadow-blur" :class="'bg-'+theme.themeColor" @tap="onCreatePoster">生成海报</button>
				</view>
			</view>
		</view>

		<view :class="'cu-modal ' + (posterShow ? 'show' : '')" >
			<view class="cu-dialog show-bg">
				<view class="bg-white" style="height: calc(100vh - 200rpx)">
					<image :src="posterUrl" class="image-box"></image>
				</view>
				<view class="cu-bar bg-white solid-top show-btn">
					<view class="action margin-0 flex-sub" @tap="hidePosterShow">取消</view>

					<!-- #ifdef MP || APP-PLUS -->
					<view class="action margin-0 flex-sub solid-left text-red text-bold" @tap="savePoster">保存到相册</view>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<view class="action margin-0 flex-sub solid-left text-red text-bold"  @tap="hidePosterShow">长按图片可保存或分享</view>
					<!-- #endif -->
				</view>
			</view>
		</view>
		<view :class="'cu-modal ' + modalRule">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">规则说明</view>
					<view class="action" @tap="ruleHide">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl text-left">
					<text>{{seckillInfo.seckillRule}}</text>
				</view>
			</view>
		</view>

		<!-- #ifdef H5 || APP-PLUS -->
		<!-- 二维码组件，不显示，只用来生成二维码调用 说明文档 https://github.com/q310550690/uni-app-qrcode -->
		<!-- 该组件生成二维码时需要canvas元素装载,固直接引用组件没有使用js，效果一样 -->
		<tki-qrcode ref="qrCodeRef" :size="200" :val="curLocalUrl" :show="false" @result="startCreatePoster"  icon="/static/public/logo.png"></tki-qrcode>
		<!-- #endif -->

	</view>
</template>

<script>

	import shopInfo from "@/components/shop-info/index";
	const util = require("@/utils/util.js");
	const {
		base64src
	} = require("@/utils/base64src.js");
	const app = getApp();
	import api from '@/utils/api'
	import numberUtil from '@/utils/numberUtil.js'
	import dateUtil from '@/utils/dateUtil.js'
	import jweixin from '@/utils/jweixin'
	import poster from "@/components/wxa-plugin-canvas/poster/index";
	import countDown from "@/components/count-down/index";
	import tkiQrcode from "@/components/tki-qrcode/tki-qrcode.vue"
	import shareFriends from "@/components/share-friends/index"


	export default {

		computed:{
		},
		data() {
			return {
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				dateUtil: dateUtil,
				numberUtil: numberUtil,
				seckillInfo: {
					shopInfo:{},
					name:'',
					seckillNum: 0,
					hallTime: 0,
					goodsSpu: {
						freightTemplat: {}
					},
					goodsSku: {
						specs: []
					},
				},
				disabled: false,
				parameter: {},
				shareShow: '',
				curLocalUrl: '',
				userInfo: null,
				modalRule: '',
				seckillHallInfoId: "",
				specInfo: "",
				cutPercent: "",
				canCutPrice: "",
				havCutPrice: "",
				posterUrl: "",
				posterShow: false,
				posterConfig: "",
				article_description: "",
				hasBargainUser: false, //是否存在砍价数据
				bargainUserId: '',
				curHour: 0,
				outTime: -1,
				nextCountDown: -1,//如果该商品详情是暂未开始的商品那么获取自动启动倒计时
				shopInfo:{},
				shopId:''
			};
		},

		components: {
			poster,
			countDown,
			tkiQrcode,
			shareFriends,
		},
		props: {},
		onShow() {
			this.seckillInfoGet();
		},
		onLoad(options) {
      // console.log(options)
			this.dateUtil = dateUtil;
			this.numberUtil = numberUtil;
			this.curHour = this.$moment().format("H");
      let seckillHallInfoId;
      if(options.shopId){
        this.shopId = options.shopId
        this.shopInfoGet(options.shopId)
      }
      if(options.referee){
        let params = {
          referee: options.referee,
          wxUseropenId: uni.getStorageSync('user_info').wxUseropenId
        }
        this.bindSpread(params)
      }
			if (options.scene) {
        //接受二维码中参数
				seckillHallInfoId = decodeURIComponent(options.scene)
			} else {
				if(options.seckillHallInfoId){
					seckillHallInfoId = options.seckillHallInfoId;
				}else if(options.id){
					seckillHallInfoId = options.id;
				}
			}
			this.seckillHallInfoId = seckillHallInfoId;
			app.initPage().then(res => {
				this.userInfo = uni.getStorageSync('user_info');
			});

		},

		onShareAppMessage: function() {
			let seckillInfo = this.seckillInfo;
			let title = seckillInfo.shareTitle;
			let imageUrl = seckillInfo.picUrl;
			let path = 'pages_grid/pages/seckill/seckill-detail/index?seckillHallInfoId=' + (this.seckillHallInfoId +"&referee=" +uni.getStorageSync("user_info").refereeId || "") + '&shopId='+this.shopId;
       return {
				title: title,
				path: path,
				imageUrl: imageUrl,
				success: function(res) {
					if (res.errMsg == 'shareAppMessage:ok') {
						console.log(res.errMsg);
					}
				},
				fail: function(res) { // 转发失败
				}
			};
		},
		methods: {
			//推荐人绑定
			bindSpread(data) {
				console.log(`推荐人绑定参数`, data)
				api.bindSpread(data).then(res => {
					console.log(`推荐人绑定接口返回参数`, res)
				});
			},
			//查询店铺
			shopInfoGet(shopId) {
				api.shopInfoGet(shopId).then(res => {
					this.shopInfo = res.data;
				});
			},
			//查询秒杀详情
			seckillInfoGet() {
				api.seckillInfoGet(this.seckillHallInfoId).then(res => {
					res.data.goodsSpu.freightTemplat = res.data.goodsSpu.freightTemplat? res.data.goodsSpu.freightTemplat : {}
					if(res.data.seckillHall){
						let hallHour = Number(res.data.seckillHall.hallTime);
						let curDate = this.$moment().format("YYYY-MM-DD");
						// 必须当前日期和当前时间相同才能进行秒杀
						if(curDate==res.data.seckillHall.hallDate){
							// 计算倒计时时间
							let curDateTime = new Date().getTime();//当前时间
							if(hallHour==this.curHour){
								let nextHour = hallHour + 1;
								let nextDateTime = res.data.seckillHall.hallDate + ' ' + nextHour + ':00:00';
								let timeTemp = this.$moment(nextDateTime).toDate();
								this.outTime = new Date(timeTemp).getTime() - curDateTime;//下一个整点时间
							} else if(hallHour>this.curHour){
								//还未开始的也要启动倒计时，例如，当我59进到该详情页面时不能秒杀购买，但是在该页面等一分钟后该商品应该自动变为可以秒杀购买
								this.outTime=0;
								let startDateTime = res.data.seckillHall.hallDate + ' ' + hallHour + ':00:00';
								let timeTemp = this.$moment(startDateTime).toDate();
								let nextCountDown = new Date(timeTemp).getTime() - curDateTime;//下一个整点时间
								this.nextCountDown = nextCountDown/1000;
								var that = this;
								let timer = setInterval(function() {//启动倒计时
									that.nextCountDown--
									if (that.nextCountDown == 0) {
										//结束,刷新
										clearInterval(timer);
										that.seckillInfoGet();
									}
								}, 1000);
							}
						}
					}
					let specInfo = '';
					res.data.goodsSku.specs.forEach(function(specItem, index) {
						specInfo = specInfo + specItem.specValueName;
						if (res.data.goodsSku.specs.length != index + 1) {
							specInfo = specInfo + ';';
						}
					});
					this.specInfo = specInfo;
					this.seckillInfo = res.data;

					setTimeout(() => {
						this.article_description = this.seckillInfo.goodsSpu ? this.seckillInfo.goodsSpu.description:'';
					}, 300);
					// #ifdef H5
					this.curLocalUrl = window.location.href;
					// #endif
				});
			},
			//立即秒杀
			toSeckillBuy(e) {
				let seckillInfo = this.seckillInfo;
				if (this.outTime<1) {
					uni.showToast({
						title: '当前时间不能发起秒杀！',
						icon: 'none'
					})
					return;
				}
				let goodsSpu = seckillInfo.goodsSpu;
				let goodsSku = seckillInfo.goodsSku;
				console.log(seckillInfo,'seckillInfo.goodsSku;')
				if (seckillInfo.limitNum > seckillInfo.seckillNum) {
					/* 把参数信息异步存储到缓存当中 */
					uni.setStorage({
						key: 'param-orderConfirm',
						data: [{
							spuId: goodsSpu.id,
							skuId: goodsSku.id,
							quantity: 1,
							salesPrice: seckillInfo.seckillPrice,
							spuName: goodsSpu.name,
							specInfo: this.specInfo,
							picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
							freightTemplat: goodsSpu.freightTemplat,
							weight: goodsSku.weight,
							volume: goodsSku.volume,
							orderType: '3',
							marketId: seckillInfo.id,
							relationId: seckillInfo.seckillHall.id,
							shopInfo: this.shopInfo
						}]
					});
					uni.navigateTo({
						url: '../seckill-order-confirm/index'
					});
				} else {
					uni.showToast({
						title: '秒杀商品库存不足',
						icon: 'none',
						duration: 2000
					});
				}
			},
			//原价购买
			tobuy() {
				let seckillInfo = this.seckillInfo;
				let goodsSpu = seckillInfo.goodsSpu;
				let goodsSku = seckillInfo.goodsSku;
				let specInfo = this.specInfo;
				/* 把参数信息异步存储到缓存当中 */

				uni.setStorage({
					key: 'param-orderConfirm',
					data: [{
						spuId: goodsSpu.id,
						skuId: goodsSku.id,
						quantity: 1,
						salesPrice: goodsSku.salesPrice,
						spuName: goodsSpu.name,
						specInfo: specInfo,
						picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
						pointsDeductSwitch: goodsSpu.pointsDeductSwitch,
						pointsDeductScale: goodsSpu.pointsDeductScale,
						pointsDeductAmount: goodsSpu.pointsDeductAmount,
						pointsGiveSwitch: goodsSpu.pointsGiveSwitch,
						pointsGiveNum: goodsSpu.pointsGiveNum,
						freightTemplat: goodsSpu.freightTemplat,
						weight: goodsSku.weight,
						volume: goodsSku.volume,
						shopInfo: this.shopInfo
					}]
				});
				uni.navigateTo({
					url: '/pages/order/order-confirm/index'
				});
			},
			shareShowFun() {
				// #ifdef H5
				this.curLocalUrl = window.location.href;
				// #endif
				// #ifdef APP-PLUS
				this.curLocalUrl = util.setAppPlusShareUrl();
				// #endif
				this.shareShow = 'show';
			},

			shareHide() {
				this.shareShow = '';
			},

			onPosterSuccess(e) {
				this.posterUrl = e;
				this.posterShow = true;
			},

			onPosterFail(err) {
				console.error(err);
			},

			hidePosterShow() {
				this.posterShow = false;
				this.shareShow = '';
			},
			/**
			 * 异步生成海报
			 */
			onCreatePoster() {
				// #ifdef MP
				api.qrCodeUnlimited({
					theme: app.globalData.theme, //全局颜色变量
          page: 'pages_grid/pages/seckill/seckill-detail/index',
          scene: `${this.seckillHallInfoId}`
				}).then(res => {
					base64src(res.data, res => {
						this.startCreatePoster(res);
					});
				});
				// #endif
				// #ifdef H5 || APP-PLUS
				uni.showLoading({
					title: '海报生成中',
					mask: true
				});
				this.$refs.qrCodeRef._makeCode(); // H5需要先生成二维码后 才能生成海报
				// #endif
			},
			startCreatePoster(res) { // 开始 生成海报
				let desc = '长按识别小程序码';

				let shareImg = this.seckillInfo.picUrl;
				// #ifdef H5 || APP-PLUS
					desc = '长按识别二维码';
					// h5的海报分享的图片有的有跨域问题，所以统一转成base64的
					// 之所以不在组件里面转换是因为无法区分哪张image图片需要处理，一般处理主图
					shareImg = util.imgUrlToBase64(shareImg);
				// #endif
					let qrCode = res; //海报配置请参考 https://github.com/jasondu/wxa-plugin-canvas
					let posterConfig = {
						width: 750,
						height: 1280,
						backgroundColor: '#fff',
						debug: false,
						blocks: [{
							width: 690,
							height: 808,
							x: 30,
							y: 183,
							borderWidth: 2,
							borderColor: '#f0c2a0',
							borderRadius: 20
						}, {
							width: 634,
							height: 74,
							x: 59,
							y: 770,
							backgroundColor: '#fff',
							opacity: 0.5,
							zIndex: 100
						}],
						texts: [{
							x: 30,
							y: 113,
							baseLine: 'top',
							text: this.seckillInfo.shareTitle,
							fontSize: 38,
							color: '#080808'
						}, {
							x: 92,
							y: 810,
							fontSize: 38,
							baseLine: 'middle',
							text: this.seckillInfo.goodsSpu.name,
							width: 570,
							lineNum: 1,
							color: '#080808',
							zIndex: 200
						}, {
							x: 59,
							y: 895,
							baseLine: 'middle',
							text: [{
								text: '秒杀价',
								fontSize: 28,
								color: '#ec1731'
							}, {
								text: '¥' + this.seckillInfo.seckillPrice,
								fontSize: 36,
								color: '#ec1731',
								marginLeft: 30
							}]
						}, {
							x: 522,
							y: 895,
							baseLine: 'middle',
							text: '原价 ¥' + this.seckillInfo.goodsSku.salesPrice,
							fontSize: 28,
							color: '#929292'
						}, {
							x: 59,
							y: 945,
							baseLine: 'middle',
							text: [{
								text: this.seckillInfo.goodsSpu.sellPoint,
								fontSize: 28,
								color: '#929292',
								width: 570,
								lineNum: 1
							}]
						}, {
							x: 360,
							y: 1065,
							baseLine: 'top',
							text: desc,
							fontSize: 38,
							color: '#080808'
						}, {
							x: 360,
							y: 1123,
							baseLine: 'top',
							text: '限时秒杀，抢到就是赚到！',
							fontSize: 28,
							color: '#929292'
						}],
						images: [{
							width: 634,
							height: 634,
							x: 59,
							y: 210,
							url: shareImg
						}, {
							width: 220,
							height: 220,
							x: 92,
							y: 1020,
							url: qrCode
						}]
					};
					let userInfo = uni.getStorageSync('user_info');

					if (userInfo && userInfo.headimgUrl) {
						//如果有头像则显示
						posterConfig.images.push({
							width: 62,
							height: 62,
							x: 30,
							y: 30,
							borderRadius: 62,
							url: userInfo.headimgUrl
						});
						posterConfig.texts.push({
							x: 113,
							y: 61,
							baseLine: 'middle',
							text: userInfo.nickName,
							fontSize: 32,
							color: '#8d8d8d'
						});
					}
					this.posterConfig = posterConfig;
					this.posterShow = true;
					this.$refs.posterRef.onCreate(false, this.posterConfig); // 入参：true为抹掉重新生成
			},
			//点击保存到相册
			savePoster: function() {
				var that = this;
				uni.saveImageToPhotosAlbum({
					filePath: that.posterUrl,
					success(res) {
						uni.showModal({
							content: '图片已保存到相册，赶紧晒一下吧~',
							showCancel: false,
							confirmText: '好的',
							confirmColor: '#333',
							success: function(res) {
								if (res.confirm) {
									/* 该隐藏的隐藏 */
									that.shareShow = '';
								}
							},
							fail: function(res) {
								console.log(res);
							}
						});
					}

				});
			},
			ruleShow() {
				this.modalRule = 'show';
			},
			ruleHide() {
				this.modalRule = '';
			},
			countDownDone() {
				this.seckillInfoGet();
			}
		}
	};
</script>
<style>
	.seckill-image{
		width: 100%;
		height: calc(100vw);
	}
	.show-bg{
		height: 84%;
		margin-top: 120rpx;
	}

	.image-box{
		height: 90%;
	}

	.show-btn{
		margin-top: -130rpx;
	}
</style>
